home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / minix / update~4.z / update~4 / lib_stdio_fgets.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-09-06  |  1.6 KB  |  59 lines

  1. /*                f g e t s
  2.  *
  3.  * Read a line from the specified stream. The function will read
  4.  * characters until n-1 characters are read or a newline character
  5.  * is read or an EOF is encountered. The string is then terminated
  6.  * with a null character. The newline character is placed into the
  7.  * string, unlike gets which strips the newline character. The
  8.  * function returns the first argument, but will return the NULL
  9.  * pointer if no character was read before EOF was read.
  10.  *
  11.  * Patchlevel 1.0
  12.  *
  13.  * Edit History:
  14.  * 02-Sep-1989    Speed up by retrieving directly from buffer.
  15.  */
  16.  
  17. #include "stdiolib.h"
  18.  
  19. /*LINTLIBRARY*/
  20.  
  21. char *fgets(buf, n, fp)
  22.  
  23. char *buf;                /* buffer for input */
  24. int n;                    /* size of buffer */
  25. FILE *fp;                /* stream */
  26.  
  27. {
  28.   int ch;                /* character read */
  29.   unsigned char *q;            /* input buffer pointer */
  30.   unsigned char *s;            /* output buffer */
  31.   unsigned int bytesleft;        /* bytes left in current load */
  32.  
  33.   if (n <= 1)
  34.     return n > 0 ? (buf[0] = 0, buf) : NULL;
  35.  
  36.   if (fp == stdin && TESTFLAG(stdout, _IOLBF))
  37.     (void) fflush(stdout);
  38.  
  39.   for (s = (unsigned char *) buf, --n; ; ) {
  40.     if ((bytesleft = BYTESINREADBUFFER(fp)) != 0) {
  41.       if (bytesleft > n)
  42.     bytesleft = n;
  43.       n -= bytesleft;
  44.       q = GETREADPTR(fp);
  45.       UNROLL_DO(fgetsbytes, bytesleft, if ((*s++ = *q++) == '\n') break);
  46.       SETREADPTR(fp, q);
  47.     }
  48.     *s = 0;
  49.     if (bytesleft != 0 || n == 0)
  50.       return buf;
  51.     if ((ch = getc(fp)) == EOF)
  52.       return s == (unsigned char *) buf ? NULL : buf;
  53.     if ((*s++ = ch) == '\n' || --n == 0) {
  54.       *s = 0;
  55.       return buf;
  56.     }
  57.   }
  58. }
  59.